package com.leo.servlet;

import com.alibaba.fastjson.JSONObject;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * Created by luomhy on 2016-2-1.
 */

@ServerEndpoint("/ws")
public class WebSocketTest {

    //临时池
    private static Set<WebSocketTest> pool = new CopyOnWriteArraySet<>();

    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        pool.add(this);
        System.out.println("客户端开始连接");
    }

    @OnClose
    public void onClose() {
        System.out.println("客户端关闭连接");
    }

    @OnMessage
    public void onMessage(String message, Session session)
            throws IOException, InterruptedException {
        String id = session.getId();
        System.out.println(String.format("ID:%s",id));
        System.out.println(String.format("服务收到:%s",message));

        JSONObject rs = new JSONObject();
        rs.put("msg",message);
        rs.put("id",id);
        lx(rs.toJSONString());
    }

    public void lx(String rs){
        for(WebSocketTest that:pool){
            try {
                Session temp = that.session;
                temp.getBasicRemote().sendText(rs);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

}
